﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using System.Reflection;
using System.Web.Http.Dispatcher;

namespace UsageTracker.Service
{
    using System.Configuration;
    using System.IO;

    class ExtControllerResolver : IAssembliesResolver
    {
        private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public ICollection<System.Reflection.Assembly> GetAssemblies()
        {
            log.Info("Trying to load external WebAPI controller(s) from external assemblies.");
            List<Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

            try
            {
                string extAsmLocation = ConfigurationManager.AppSettings.Get("EXT_CONTROLLER_ASM_PATH");
                log.Info(Path.Combine(extAsmLocation, "UsageTracker.Server.dll"));
                var controllersAssembly = Assembly.LoadFrom(Path.Combine(extAsmLocation, "UsageTracker.Server.dll"));

                log.Info("Loaded external controller assembly - " + controllersAssembly.FullName + " from path: "
                    + controllersAssembly.Location);
                baseAssemblies.Add(controllersAssembly);
            }
            catch (TypeLoadException typExp)
            {
                log.Error("Type Load Exception: " + typExp.Message + "\n" + typExp.TypeName + typExp.StackTrace);
            }
            catch (Exception exp)
            {
                log.Error("Could not resolve/load the external controller assemblies from the path specified. Please check the appSettings parameter [EXT_CONTROLLER_ASM_PATH] in the .CONFIG file. Details: " + exp.Message + "\n" + exp.StackTrace);
            }
            return baseAssemblies;
        }
    }
}
